package com.octopus.samples.douban;

import com.octopus.core.Request;
import com.octopus.core.Response;
import com.octopus.core.parser.JsonParser;
import com.octopus.core.parser.ParseException;
import com.octopus.core.parser.ParseResult;
import com.octopus.core.result.Result;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 电影列表解析
 *
 * @author shoulai.yang@gmail.com
 * @date 2019/08/02
 */
public class SubjectsParser extends JsonParser {

  @Override
  public ParseResult parse(JSONObject json, Response response) throws ParseException {
    JSONArray subjects = json.getJSONArray("subjects");
    List<Request> requests = new ArrayList<>();
    if (subjects != null) {
      int size = subjects.length();
      int page = response.request().extras().getInteger("page");
      String tag = response.request().extras().getString("tag");
      if (size == 20) {
        requests.add(
            Request.me(
                    String.format(
                        "https://movie.douban.com/j/search_subjects?type=movie&tag=%s&sort=time&page_limit=20&page_start=%s",
                        tag, (page + 1)))
                .extra("page", page + 1)
                .extra("tag", tag));
      }
    }
    return ParseResult.me().body(Result.me().obj(subjects)).requests(requests);
  }
}
